package com.ds.service;

import com.ds.dao.UserDao;
import com.ds.model.AjaxResult;
import com.ds.model.User;
import jakarta.servlet.http.HttpServletRequest;

import java.sql.SQLException;

public class UserService {
    private final UserDao userDao = new UserDao();
    /**
     * 这是具体的登录方法
     * 1.首先根据用户名查询用户信息
     * 2.判断用户状态是否 OK
     * 3.判断密码是否 OK
     * @param user
     * @return
     */
    public AjaxResult login(User user, HttpServletRequest req) {
        try {
            //获取验证码
            String code = (String) req.getSession().getAttribute("code");
            //获取前端传来的验证码
            String codeParam = req.getParameter("code");
            if (codeParam == null || "".equals(codeParam) || !codeParam.equalsIgnoreCase(code)){
                return AjaxResult.error("验证码错误" + "code=" + code);
            }
            User u = userDao.loadUserByUsername(user.getUsername());
            if (u == null){
                return AjaxResult.error("用户名不存在，登录失败！");
            }else {
                if (!u.getEnabled()){
                    //说明用户账户被禁用了
                    return AjaxResult.error("改用户被禁用，登录失败！");
                }
                if (user.getPassword().equals(u.getPassword())){
                    //登录成功将当前用户信息存入session
                    req.getSession().setAttribute("loginUser", u);
                    u.setPassword(null);
                    return AjaxResult.ok("登录成功",u);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return AjaxResult.error("登录失败");
    }
}
